import React from 'react';

import { Input, Button, Form, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import { reqLogin } from '../../../api';
import memory from '../../../utils/memoryUtils';
import storage from '../../../utils/storageUtils';


export default function LoginForm(props) {

    const { history } = props;

    return (
        <Form name="control-hooks" onFinish={(vals) => submit(vals, history)}>
            <Form.Item name="username" rules={[
                { required: true, validator: checkUserName },
                // { required: true, whitespace: true, message: '请输入用户名!' },
                // { min: 4, message: '用户名最少4位' },
                // { max: 12, message: '用户名最多12位' },
                // { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须由字母、数字或下划线组成' },
            ]} >
                <Input prefix={<UserOutlined />} autoFocus={true} placeholder="用户名" autoComplete="off" />
            </Form.Item>

            <Form.Item name="password" rules={[
                { required: true, whitespace: true, message: '请输入密码!' },
            ]} >
                <Input.Password prefix={<LockOutlined />} type="password" placeholder="密码" autoComplete="off" />
            </Form.Item>

            <Form.Item>
                <Button type="primary" className="btn" htmlType="submit">登录</Button>
            </Form.Item>
        </Form>
    )
}

async function submit(vals, history) {
    const { username, password } = vals;

    const res = await reqLogin(username, password);

    if (res.status === 0) {
        message.success(`登录成功！欢迎您，${username}！`);
        // 保存用户数据到内存中
        memory.user = res.data;
        storage.saveUser(res.data);
        history.replace('/');
    } else {
        message.error(res.msg);
    }
}

function checkUserName(_, val) {
    if (!val) {
        return Promise.reject('请输入用户名！');
    }

    if (!/^[a-zA-Z0-9_]+$/.test(val)) {
        return Promise.reject('用户名必须由字母、数字或下划线组成');
    }

    if (val.length < 4) {
        return Promise.reject('用户名最少4位');
    } else if (val.length > 12) {
        return Promise.reject('用户名最多12位');
    }

    return Promise.resolve();
}
